package com.hctforgreen.greenservice;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.db.DBManager;
import com.hctforgreen.greenservice.machineManager.impl.Bigunit;
import com.hctforgreen.greenservice.machineManager.impl.JY_HotWaterMachine;
import com.hctforgreen.greenservice.machineManager.impl.MutipleMachine;
import com.hctforgreen.greenservice.machineManager.impl.SY_HotWaterMachine;
import com.hctforgreen.greenservice.model.BigUnitEntity;
import com.hctforgreen.greenservice.model.BookListEntity;
import com.hctforgreen.greenservice.model.BootPasswordEntity;
import com.hctforgreen.greenservice.model.IndustryEntity;
import com.hctforgreen.greenservice.model.JYHotWaterMachineEntity;
import com.hctforgreen.greenservice.model.LocationEntity;
import com.hctforgreen.greenservice.model.MutipleMachineEntity;
import com.hctforgreen.greenservice.model.PwdEntity;
import com.hctforgreen.greenservice.model.RelevanceEntity;
import com.hctforgreen.greenservice.model.SYHotWaterMachineEntity;
import com.hctforgreen.greenservice.model.SubmitBigUnitInfoEntity;
import com.hctforgreen.greenservice.ui.widget.ListViewIsChildOfScrollView;
import com.hctforgreen.greenservice.utils.CheckDataVersionCodeUtil;
import com.hctforgreen.greenservice.utils.DownloadBookLstInitFinishUtil;
import com.hctforgreen.greenservice.utils.EntryCatalogUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.Utils;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 * 机型关联提示--关联资料详情
 * 阅读完毕获取开机密码
 * Created by 390697 on 2016/11/19.
 */
public class MachineRelevanceTipActivity extends ParentActivity implements View.OnClickListener {
    //含有开机密码所有的信息的实体类
    private PwdEntity pwdEntity;
    //抽象的list 包含bookList,vedioList
    private List<Object> objList;
    private List<RelevanceEntity.BookClass> bookList;
    private List<RelevanceEntity.VedioClass> vedioList;

    private int MachineType;//机型类型
    /**
     * 登录标识，用于判断登录掌上通正式服务器的次数，超过1次则判断为正式服务器宕机
     */
    public int pingCount = 0;
    /**
     * false为正式服务器，true为云服务器
     */
    private boolean isCloudServer = false;
    /**
     * DBManager数据库管理
     */
    private DBManager mgr;
    private MutipleMachine mutipleMachine;//多联机管理类
    private SY_HotWaterMachine sy_HotWaterMachine;//商用热水机管理类
    private JY_HotWaterMachine jy_HotWaterMachine;//家用热水机管理类
    private Bigunit bigunit;//大机组管理类

    private MutipleMachineEntity mutipleMachineEntity;//多联机特殊属性实体类
    private JYHotWaterMachineEntity jyHotWaterMachineEntity;
    private SYHotWaterMachineEntity syHotWaterMachineEntity;
    private BigUnitEntity bigUnitEntity;

    private LocationEntity locationEntity;
    private IndustryEntity industryEntity;
    private boolean isGREEDAQ;

    private MachineRelevanceTipActivity machineRelevanceTipActivity;
    Button finishBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.relevance_tip_layout);
        machineRelevanceTipActivity = this;
        initSkinLayout();
        initData();
        findViews();
        mgr = new DBManager(MachineRelevanceTipActivity.this);
        isUpdateBooksServiceRunning();
    }

    private void initData() {
        objList = new ArrayList<Object>();
        //从intent拿数据 解析显示
        Intent intent = getIntent();
        pwdEntity = intent.getParcelableExtra("PwdEntity");
        MachineType = intent.getIntExtra("MachineType", 0);
        switch (MachineType){
            // 1:多联机 2:家用热水机 3：商用热水机 4：大机组0：其它
            case 1:
                mutipleMachineEntity = (MutipleMachineEntity) intent.getSerializableExtra("mutipleMachine");
                break;
            case 2:
                jyHotWaterMachineEntity =(JYHotWaterMachineEntity) intent.getSerializableExtra("jy_HotWaterMachine");
                break;
            case 3:
                syHotWaterMachineEntity = (SYHotWaterMachineEntity) intent.getSerializableExtra("sy_HotWaterMachine");
                break;
            case 4:
                bigUnitEntity = (BigUnitEntity) intent.getSerializableExtra("bigunit");
                break;
            case 0:

                break;
            default:break;
        }

        pingCount = getIntent().getIntExtra("PING_COUNT", 0);
        isCloudServer = getIntent().getBooleanExtra("WHICH_SERVER", false);
        bookList = (List) intent.getSerializableExtra("bookList");
        vedioList = (List) intent.getSerializableExtra("vedioList");

        locationEntity = (LocationEntity) getIntent().getSerializableExtra("locationEntity");
        industryEntity = (IndustryEntity) getIntent().getSerializableExtra("industryEntity");
        isGREEDAQ = getIntent().getBooleanExtra("isGREEDAQ",false);

        if (bookList != null && bookList.size() != 0) {
            for (RelevanceEntity.BookClass bookClass : bookList) {
                objList.add(bookClass);
            }
        }

        if (vedioList != null && vedioList.size() != 0) {
            for (RelevanceEntity.VedioClass vedioClass : vedioList) {
                objList.add(vedioClass);
            }
        }

        mutipleMachine = new MutipleMachine(this);//初始化多联机相应的组件
        sy_HotWaterMachine = new SY_HotWaterMachine(this);//初始化商用热水机相应的组件
        jy_HotWaterMachine = new JY_HotWaterMachine(this);//初始化家用热水机相应的组件
        bigunit = new Bigunit(this);//初始化大机组相应的组件
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void findViews() {
        ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
        scrollView.smoothScrollTo(0, 0);
        TextView title = (TextView) findViewById(R.id.tv_title);
        ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
        finishBtn = (Button) findViewById(R.id.finish_read_btn);
        ListViewIsChildOfScrollView materialsLv = (ListViewIsChildOfScrollView) findViewById(R.id.relevance_lv);
        MaterialsAdapter adapter = new MaterialsAdapter(MachineRelevanceTipActivity.this, objList);
        materialsLv.setAdapter(adapter);

        title.setText(R.string.relevance_materials);
        backBtn.setOnClickListener(this);
        finishBtn.setOnClickListener(this);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
//                Intent intent = new Intent(MachineRelevanceTipActivity.this,StartPwdActivity.class);
//                startActivity(intent);
                finish();
                break;
            case R.id.finish_read_btn:
                //获取开机密码：
                getBootPwd(pwdEntity);
                break;
        }
    }

    /**
     * 2016-12-30
     * 390694 增加判断更新资料的服务是否正在更新，
     * 更新：提示正在更新资料包，不能查询阅读;
     * 不更新：若数据库已更新且资料包版本不是最新，则可以查询阅读；
     * ****  若资料包版本不是最新，则提示去下载管理更新
     */
    public void isUpdateBooksServiceRunning(){
        boolean isServiceRunning = DownloadBookLstInitFinishUtil.getUpdateBookServiceFinished(machineRelevanceTipActivity);
        CheckDataVersionCodeUtil checkDataVersionCodeUtil = new CheckDataVersionCodeUtil();
        if (isServiceRunning){
            Dialog dialog = null;
            AlertDialog.Builder builder = new AlertDialog.Builder(machineRelevanceTipActivity);
            builder.setTitle(R.string.dialog_default_title_hint)
                    .setMessage(R.string.update_now)
                    .setPositiveButton(R.string.dialog_confirm_hint,
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.dismiss();
                                }
                            });
            dialog = builder.create();
            dialog.show();
        }else{
            checkDataVersionCodeUtil.new CheckDataVersionCodeTask(R.string.debug_activity_update_data_content,
                    R.string.terminal_update_data_title_2, machineRelevanceTipActivity, true,
                    null, null, null, null, null).execute(machineRelevanceTipActivity);

        }

    }

    /**
     * 获取开机密码
     **/
    private void getBootPwd(final PwdEntity paramEntity) {

        final ProgressBar loadPb = (ProgressBar) findViewById(R.id.pb_loadings);
        finishBtn.setClickable(false);
        loadPb.setVisibility(View.VISIBLE);
        MobclickAgent.onEvent(this, "Submit_start_pwd");
        final Handler handler = new Handler() {
            public void handleMessage(Message msg) {
                finishBtn.setClickable(true);
               loadPb.setVisibility(View.GONE);
                ArrayList<PwdEntity> pwdlist = new ArrayList<PwdEntity>();
                HctResult hctResult = new HctResult();
                switch (msg.what) {
                    case HctConstants.STATUS_SUCCESS:
                        hctResult = (HctResult) msg.obj;
                        // 先判断是否是大机组提交数据
                        if (hctResult.isBigUnit) {// 大机组点击提交时获取开机密码处理动作
                            SubmitBigUnitInfoEntity mBigUnitPasswordEntity = (SubmitBigUnitInfoEntity) hctResult.data;

                            if (mBigUnitPasswordEntity.statusCode.equals("0")) {

                                paramEntity.date = Utils.getNowDate();
                                paramEntity.identityCode = bigUnitEntity.identityCode;
                                paramEntity.isBigUnit = "1";
                                paramEntity.time = Utils.getNowTimeHM();
                                paramEntity.stripeCode = paramEntity.stripeCode.split(",")[0];
                                paramEntity.sparebootPwd = "";
                                paramEntity.finished = "0";

                                paramEntity.industry = industryEntity.name;//保存本地时，行业存中文

                                pwdlist.add(paramEntity);

                                // 保存到本地数据库
                                mgr.add(pwdlist);


                            } else if (!mBigUnitPasswordEntity.statusCode
                                    .equals("0")) {
                                if (!mBigUnitPasswordEntity.unitMsg.equals("")) {
                                    Toast.makeText(MachineRelevanceTipActivity.this,
                                            mBigUnitPasswordEntity.unitMsg,
                                            Toast.LENGTH_SHORT).show();
                                } else if (mBigUnitPasswordEntity.unitMsg
                                        .equals("")) {

                                    Toast.makeText(MachineRelevanceTipActivity.this,
                                            getString(R.string.net_error_hint),
                                            Toast.LENGTH_SHORT).show();
                                }
                                break;
                            }
                        } else {// 其他机型点击提交时获取开机密码处理。其他机型获取的开机密码
                            BootPasswordEntity mBootPasswordEntity = (BootPasswordEntity) hctResult.data;
                            if (mBootPasswordEntity.statusCode.equals("0")) {

							/*
                             * 修改获取开机密码 wuhs 20150715
							 */
                                String[] mas = paramEntity.stripeCode.split(",");// 条码
                                String[] pds = mBootPasswordEntity.bootPwd
                                        .split(",");

                                // 先保存本地数据库
                                for (int i = 0; i < mas.length; i++) {
                                    PwdEntity entity = new PwdEntity();

                                    entity.phone = paramEntity.phone;
                                    entity.street = paramEntity.street;
                                    entity.projectName = paramEntity.projectName;
                                    entity.ownerName = paramEntity.ownerName;
                                    entity.ownerPhone = paramEntity.ownerPhone;
                                    entity.remark = paramEntity.remark;

                                    entity.stripeCode = mas[i];
                                    entity.industry = industryEntity.name;//保存本地时，行业存中文
                                    entity.province = locationEntity.getProvince();
                                    entity.city = locationEntity.getCity();
                                    entity.district = locationEntity.getDistrict();
                                    entity.date = Utils.getNowDate();
                                    entity.openPassword = pds[i]
                                            .replace("[", "").replace("]", "")
                                            .replace("\"", "");
                                    entity.time = Utils.getNowTimeHM();
                                    entity.stripeCode = mas[i];
                                    entity.sparebootPwd = "";


                                    pwdlist.add(entity);
                                }
                                // 保存到本地数据库
                                mgr.add(pwdlist);


                            } else if (!mBootPasswordEntity.statusCode.equals("0")) {

                                if (!mBootPasswordEntity.bootMsg.equals("")) {
                                    Toast.makeText(MachineRelevanceTipActivity.this,
                                            mBootPasswordEntity.bootMsg,
                                            Toast.LENGTH_SHORT).show();
                                } else if (mBootPasswordEntity.bootMsg.equals("")) {
                                    Toast.makeText(MachineRelevanceTipActivity.this,
                                            getString(R.string.net_error_hint),
                                            Toast.LENGTH_SHORT).show();
                                }
                                break;
                            }

                        }

                        // 保存后跳转
                        Intent intent = new Intent();
                        intent.setClass(MachineRelevanceTipActivity.this, ShowPwdActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putParcelableArrayList("pwdlist", pwdlist);
                        //派工标志位
                        bundle.putBoolean("isGREEDAQ", isGREEDAQ);
                        intent.putExtras(bundle);
                        //传递服务器类型判断结果至开机密码列表界面
                        intent.putExtra("PING_COUNT", pingCount);
                        intent.putExtra("WHICH_SERVER", isCloudServer);
                        startActivity(intent);
                        finish();
                        break;

                    case HctConstants.STATUS_FAILD:
                        Toast.makeText(MachineRelevanceTipActivity.this, getString(R.string.net_error_hint),
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
        new Thread() {
            public void run() {
                Message message = new Message();
                try {
                    HctController controller = new HctController(MachineRelevanceTipActivity.this);
                    HctResult result = new HctResult();

                    switch (MachineType) {
                        case 0:
                            result = controller.getBootPwd(paramEntity.phone,
                                    paramEntity.stripeCode,
                                    locationEntity.getmGpsLocation(),
                                    locationEntity.getmBaseLocation(),
                                    locationEntity.getmWifiLocation(),
                                    locationEntity.getProvince_loc(),
                                    locationEntity.getCity_loc(),
                                    locationEntity.getProvince(),
                                    locationEntity.getCity(),
                                    locationEntity.getDistrict(),
                                    paramEntity.street, paramEntity.projectName,
                                    paramEntity.ownerName, paramEntity.ownerPhone,
                                    paramEntity.remark, paramEntity.industry, "",
                                    "", "", "", "", "", "", "", "", "",
                                    locationEntity.getmLatitude() + "",
                                    locationEntity.getmLongitude() + "", "", isCloudServer);
                            break;
                        case 1:
                            result = mutipleMachine.getPwdResult(paramEntity, locationEntity, isCloudServer,mutipleMachineEntity);
                            break;
                        case 2:
                            result = jy_HotWaterMachine.getPwdResult(paramEntity, locationEntity, isCloudServer,jyHotWaterMachineEntity);
                            break;
                        case 3:
                            result = sy_HotWaterMachine.getPwdResult(paramEntity, locationEntity, isCloudServer,syHotWaterMachineEntity);
                            break;
                        case 4:
                            result = bigunit.getPwdResult(paramEntity, locationEntity, isCloudServer,bigUnitEntity);
                            break;
                    }

                    if (result.status == HctConstants.STATUS_SUCCESS) {
                        message.what = result.status;
                        message.obj = result;
                    } else {
                        message.what = HctConstants.STATUS_FAILD;
                    }
                } catch (Exception e) {
                    message.what = HctConstants.STATUS_FAILD;
                    e.printStackTrace();
                }
                handler.sendMessage(message);
            }
        }.start();
    }

    class MaterialsAdapter extends BaseAdapter {
        private List<Object> list;
        private Context context;
        private DbController controller;


        public MaterialsAdapter(Context context, List list) {
            super();
            this.context = context;
            this.list = list;
            controller = new DbController(context);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public int getCount() {
            return list.size();
        }

        /**
         * {@inheritDoc}
         *
         * @param position
         * @param convertView
         * @param parent
         */
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final Object obj = list.get(position);
            ViewHolder viewHolder;
            if (convertView == null) {
                //无复用的view
                viewHolder = new ViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.item_related_book_item, null);
                viewHolder.detail_titleTv = (TextView) convertView.findViewById(R.id.related_book_name);
                viewHolder.detailLayout = (LinearLayout) convertView.findViewById(R.id.related_book_item);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            if (obj instanceof RelevanceEntity.BookClass) {
                Drawable drawable1 = getResources().getDrawable(R.drawable.book_icon);
                //必须要设置图片的边界，否则不会显示出来
                drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
                viewHolder.detail_titleTv.setCompoundDrawables(drawable1, null, null, null);
                viewHolder.detail_titleTv.setText(((RelevanceEntity.BookClass) obj).getBookName());
                viewHolder.detailLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boolean isServiceRunning = DownloadBookLstInitFinishUtil.getUpdateBookServiceFinished(context);
                        if (isServiceRunning){
                            Dialog dialog = null;
                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                            builder.setTitle(R.string.dialog_default_title_hint)
                                    .setMessage(R.string.update_now)
                                    .setPositiveButton(R.string.dialog_confirm_hint,
                                            new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog,
                                                                    int which) {
                                                    dialog.dismiss();
                                                }
                                            });
                            dialog = builder.create();
                            dialog.show();
                            return;
                        }
                        //跳转至资料详情
                        String bookId = ((RelevanceEntity.BookClass) obj).getBookId();
                        try {
                            //从数据库查找与本书相关的信息
                            BookListEntity.BookEntity bookEntity = controller.getBookEntity(bookId);
                            if (controller.isExists(bookEntity)) {
                                EntryCatalogUtil util = new EntryCatalogUtil();
                                util.startEntryCatalogActivity((Activity) context, bookEntity, true);
                            } else {
                                Toast.makeText(context, R.string.relevance_tip, Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

            } else if (obj instanceof RelevanceEntity.VedioClass) {
                Drawable drawable2 = getResources().getDrawable(R.drawable.vedio_icon);
                //必须要设置图片的边界，否则不会显示出来
                drawable2.setBounds(0, 0, drawable2.getMinimumWidth(), drawable2.getMinimumHeight());
                viewHolder.detail_titleTv.setCompoundDrawables(drawable2, null, null, null);
                viewHolder.detail_titleTv.setText(((RelevanceEntity.VedioClass) obj).getVedioName());
                viewHolder.detailLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //跳转至视频详情
                        Intent intent = new Intent(
                                context,
                                VideoPartsActivity.class);
                        intent.putExtra("videoId", ((RelevanceEntity.VedioClass) obj).getVedioId());
                        intent.putExtra("videoName",
                                ((RelevanceEntity.VedioClass) obj).getVedioName());
                        startActivity(intent);

                    }
                });

            }

            return convertView;
        }

        class ViewHolder {
            LinearLayout detailLayout;
            TextView detail_titleTv;
        }
    }
}
